package com.example.silvercare;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

import android.util.Log;
import app.kernel.api.PsgFacade;
import config.PSG_Configuration;
import consoleUi.ConsoleMgr;

public class Coalition {
	PsgFacade psgKernelFacade = null;	
	
	String defaultIP;
	int defaultPort;
	String IPPort;
	String defaultMac;
	String ID_KEY;
	
	String MSID;
	String callerId;
	String calleeId;
	/**
	 * @param args
	 * @return 
	 * @throws Exception 
	 */
	public Coalition()
	{
    	defaultIP 		= PSG_Configuration.defaultIP;
    	defaultPort 		= PSG_Configuration.defaultPort;
    	
//    	int appPort = PSG_Configuration.appPort;
    	
    	IPPort = defaultIP+":"+defaultPort;
//    	String IPPort = defaultIP+":"+appPort;
    	defaultMac = PSG_Configuration.PSGMAC;
//    	String ID_KEY = "http://"+defaultIP+ ":"+defaultPort+"/xmlrpc";
    	ID_KEY 		= "http://"+defaultMac+"/xmlrpc";
    	   	
    	//psgKernelFacade = new PsgFacade(ID_KEY, defaultIP, defaultPort);
    	
    	

		
    	MSID = "";
    	callerId = "";
    	calleeId = "";
	}
	
	static public String getFriendConnectionInfo(String email)
	{
		String result = null;
		if(email.equalsIgnoreCase("john123@gmail.com"))
			result = "10.0.2.2|12344";
		if(email.equalsIgnoreCase("bob123@gmail.com"))
			result = "10.0.2.2|12346";
		if(email.equalsIgnoreCase("alice123@gmail.com"))
			result = "10.0.2.2|12348";
		return result;
	}
	
	public void register(){
		try{
			Log.v("Coalition", "register processing");
			long beginOne = System.currentTimeMillis();
			MSID = psgKernelFacade.register(IPPort);	
			System.out.println("The registered PSG MSID is: "+MSID);
			long endOne = System.currentTimeMillis();
			long psgRegistrationTime = endOne - beginOne;
			System.out.println("[PSG Registration Time]: "+psgRegistrationTime);
			}catch(Exception ex){
			System.err.println(ex.getMessage());
		}
	}
	
	public void useless(){
    	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String cmd = null;
		try 
		{
			cmd = in.readLine();
			System.out.println("====================================");
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
        try
        {
			if(cmd.equals("R"))
			{
		    	long beginOne = System.currentTimeMillis();
		    	MSID = psgKernelFacade.register(IPPort);	
				System.out.println("The registered PSG MSID is: "+MSID);
		    	long endOne = System.currentTimeMillis();
		    	long psgRegistrationTime = endOne - beginOne;
		    	System.out.println("[PSG Registration Time]: "+psgRegistrationTime);
//		    	writeLog("psgRegistration", ""+psgRegistrationTime);
//				String MSID = consoleMgr.psgKernelFacade.register(IPPort);
//				System.out.println("The registered PSG MSID is: "+MSID);
			}
			else if(cmd.equals("C"))
			{
				for(int i = 0;i<25;i++){
//				consoleMgr.psgKernelFacade.leave();
		    	callerId = "12345:"+MSID;
		    	calleeId = "12345:"+"person@100000";
				long beginTwo = System.currentTimeMillis();
				String callbackRegistrationResult = psgKernelFacade.registerCallback(ID_KEY, callerId, calleeId);
				System.out.println("[Callback Registration Result]: "+callbackRegistrationResult);
				long endTwo = System.currentTimeMillis();
				long callbackRegistrationTime = endTwo - beginTwo;
				System.out.println("[Callback Registration Time (Same CSG)]: "+callbackRegistrationTime);
				writeLog("callbackRegistration",""+callbackRegistrationTime);
				}
			}
			else if(cmd.equals("Q"))
			{
//				consoleMgr.psgKernelFacade.leave();

				long beginTwo = System.currentTimeMillis();
				System.out.print("Please key in your Query:");
				
		    	BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
				String query = null;				
				query = in2.readLine();	
//				String query = "select name from person";
				String result =  psgKernelFacade.queryMCS(query, ID_KEY);
				System.err.println("[Query Result]: "+result);
				long endTwo = System.currentTimeMillis();
				long queryTime = endTwo - beginTwo;
				System.out.println("[Query Time (Same CSG)]: "+queryTime);
//				writeLog("callbackRegistration",""+queryTime);
			}				
			else if(cmd.equals("M"))
			{
				
				long beginThree = System.currentTimeMillis();
				psgKernelFacade.mobilityUpdate(MSID, IPPort);
				long endThree = System.currentTimeMillis();
				long mobilityUpdatingTime = endThree - beginThree;
				System.out.println("[Mobility Updating and Notification Time (same CSG and one callback)]: "+mobilityUpdatingTime);
				writeLog("mobilityUpdate",""+mobilityUpdatingTime);
//				System.out.print("Please key in your Query:");
//				
//		    	BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
//				String query = null;				
//				query = in2.readLine();
//				consoleMgr.psgKernelFacade.queryMCS(query);
			}
			else if(cmd.equals("D")){
				long beginFour = System.currentTimeMillis();
				psgKernelFacade.withdrawCallback(ID_KEY, callerId, calleeId);
				long endFour = System.currentTimeMillis();
				long callbackWithdrawingTime = endFour-beginFour;
				System.out.println("[Callback Withdrawing Time (same CSG)]: "+callbackWithdrawingTime);
				writeLog("deleteCallback",""+callbackWithdrawingTime);


			}
			else if(cmd.equals("L")){
		    	long beginFive = System.currentTimeMillis();
		    	psgKernelFacade.leave(MSID);
//				System.out.println("The registered PSG MSID is: "+MSID);
		    	long endFive = System.currentTimeMillis();
		    	long psgLeaveTime = endFive - beginFive;
		    	System.out.println("[PSG De-Registration Time]: "+psgLeaveTime);
		    	writeLog("leave",""+psgLeaveTime);
			}
			else if(cmd.equals("I")){
		    	long beginFive = System.currentTimeMillis();
		    	String result = psgKernelFacade.getIPPort(ID_KEY, MSID);
				System.out.println("The IPPort is: "+result);
		    	long endFive = System.currentTimeMillis();
		    	long psgLeaveTime = endFive - beginFive;
		    	System.out.println("[PSG De-Registration Time]: "+psgLeaveTime);
		    	writeLog("leave",""+psgLeaveTime);
			}
			else
			{
				System.out.println("Incorrect Command, please try again.");
			}
        }
        catch (Exception e)
        {
        	System.err.println(e.getMessage());
        }
	}
	
	//get updating alert
	public String getCurrentIp () throws UnknownHostException{
		String IP = ""+InetAddress.getLocalHost();
		System.out.println("The current IP is: "+IP);
		return IP;
	}
	
	// write experiment data to txt
	public static void writeLog(String fileName, String content)
    {
            try{
                FileWriter fstream = new FileWriter("D:\\Person\\"+fileName+".txt",true);
                BufferedWriter out = new BufferedWriter(fstream);
                out.write(content);
                out.write(System.getProperty( "line.separator" ));
                out.write(System.getProperty( "line.separator" ));
                //Close the output stream
                out.close();
                }
            catch (Exception e){//Catch exception if any
             System.err.println("Error: " + e.getMessage());}
    }

}
